<?php
namespace app\jobs;

use app\config\Constants;
use app\models\GoodsOrder;
use app\models\UserCredential;
use Carbon\Carbon;

class SubscribeJob {

    private static $handle_type = [Constants::ORDER_ACCEPT,Constants::ORDER_CANCEL];

    public function execute($queue,$job){
        if($job['msg_type'] != Constants::MSG_TYPE_ORDER){
            return true;
        }
        if(!in_array($job['event_type'],self::$handle_type)){
            return true;
        }

        $order = GoodsOrder::findOne(['order_no'=>$job['data']['order_no']]);
        if(!$order){
            return false;
        }

        //是否微信渠道注册
        $credential = UserCredential::findOne(['user_id'=>$order->user_id,'type'=>Constants::WECHAT]);
        if(!$credential){
            return true;
        }

        $result = false;
        if($job['event_type'] == Constants::ORDER_ACCEPT){
            $result = $this->accept($order,$credential);
        }
        if($job['event_type'] == Constants::ORDER_CANCEL){
            $result = $this->cancel($job,$order,$credential);
        }

        $data = \Yii::$app->wechat->getMiniProgram()->subscribe_message->send($result);
        return true;
    }

    //接单
    public function accept(GoodsOrder $order,UserCredential $credential){
        return [
            'touser'=>$credential->username,
            'template_id'=>"tWESqYZsVUpDlfnhKJqz47LmI2f3Uoc8DyQWGwh6X3Q",
            'page'=>'',
            'data'=>[
                'thing6'=>['value'=>$order->merchant_name],
                'phrase5'=>['value'=>'外卖订单'],
                'character_string1'=>['value'=>$order->order_no],
                'amount3'=>['value'=>$order->total_price],
                'time4'=>['value'=>Carbon::now()->toDateTimeString()],
            ],
        ];
    }

    //取消
    public function cancel($job,GoodsOrder $order,UserCredential $credential){
        $reason = [
            Constants::USER => '用户取消订单',
            Constants::MERCHANT => '商家取消订单',
            Constants::ADMIN => '客服取消订单',
        ];
        return [
            'touser'=>$credential->username,
            'template_id'=>"1BN6WUaPmF_XjCAIQ3MeOUBNZRs4qNR-b9EehW6-PtQ",
            'page'=>'',
            'data'=>[
                'character_string1'=>['value'=>$order->order_no],
                'time3'=>['value'=>$order->add_time],
                'phrase2'=>['value'=>'已取消'],
                'thing4'=>['value'=>$reason[$job['data']['cancel']]],
            ],
        ];
    }
}